import { Component, Input, OnInit } from '@angular/core';
import { ApiService } from '@core/services/http/api.service';
import { ApesMessageService } from '@shared/apes/message';
import { missing, missingOrEmpty } from '../../utils/utils';
import * as distanceInWordsToNow from 'date-fns/distance_in_words_to_now';
import * as isSameDay from 'date-fns/is_same_day';
import * as subDays from 'date-fns/sub_days';
import { UserAuthService } from '@core/services/user-auth.service';

@Component({
  selector: 'apes-chatter',
  templateUrl: 'apes-chatter.component.html',
})

export class ApesChatterComponent implements OnInit {

  /** 渲染数据 **/
  note: any[] = [];
  process: any[] = [
    // {
    //   step: '1001', describe: 'xxxxxx', state: 'one', show: false,
    //   secondary: [
    //     { number: '10000001', type: '采购订单', time: 'yyyy-MM-dd HH:mm:ss', link: '/crm.customComplain' },
    //     { number: '10000002', type: '返厂订单', time: 'yyyy-MM-dd HH:mm:ss', link: '/crm.customComplain' },
    //   ],
    // },
    // {
    //   step: '1002', describe: 'xxx', state: 'two', show: false,
    //   secondary: [
    //     { number: '10000001', type: '采购订单', time: 'yyyy-MM-dd HH:mm:ss', link: '/crm.customComplain' },
    //     { number: '10000002', type: '返厂订单', time: 'yyyy-MM-dd HH:mm:ss', link: '/crm.customComplain' },
    //   ],
    // },
  ];
  candidate: any = '';
  curTaskName: any = '';
  nodeDuration: any = '';
  postDate: any;

  /** 展示数量 **/
  displayUntil: number = 0;
  isShowMore: boolean = true;

  /** 当前展示 **/
  showTabNow: any = '';

  /** 日志数据 **/
  @Input() notes: any[] = [];

  /** 主数据 **/
  @Input() model: any;

  /** 流程实例编号 **/
  private _processInstanceId: any;

  /** 评论**/
  remark: string = '';
  showCommentLog: boolean = false;
  _src: any = null;  // OA流程图

  constructor(private msg: ApesMessageService,
              private apiService: ApiService,
              private userAuthService: UserAuthService) {
  }

  ngOnInit() {
  }

  /** 初始化加载更多 **/
  initLogMore() {
    let sum = this.notes.length;
    let now = this.displayUntil;
    if (sum <= 5) {
      // now = sum - 1;
      now = sum;
      this.isShowMore = false;
      // } else if (sum >= 5 && now < 4) {
    } else if (sum > 5) {
      if (now < sum && now < 6) {
        now = 5;
        this.isShowMore = true;
      } else {
        now = sum;
      }
    }
    this.displayUntil = now;
  }

  /** 点击加载更多 **/
  checkLogMore() {
    // if (this.displayUntil < this.notes.length - 1) {
    //   this.displayUntil += 1;
    //   if (this.displayUntil == this.notes.length - 1) {
    //     this.isShowMore = false;
    //   }
    // } else {
    //   this.isShowMore = false;
    // }
    // this.displayUntil = this.notes.length - 1;
    this.displayUntil = this.notes.length;
    this.isShowMore = false;
  }

  checkMissionMore(params) {
    params.show = !params.show;
    // this.showTabMain = !this.showTabMain;
  }


  showTab(step) {
    if (this.showTabNow == step) {
      this.showTabNow = '';
    } else {
      this.showTabNow = step;
    }
  }

  initNotes() {
    this.note = [];
    this.initLogMore();
    // for (let i = 0; i <= this.displayUntil; i++) {
    for (let i = 0; i < this.displayUntil; i++) {
      this.note[i] = this.notes[i];
    }
    return this.note;
  }

  initProcess() {
    this.process = [];
    this.process = [
      { test: '1', name: '2' },
      { test: '1', name: '2' },
    ];
    return this.process;
  }

  initAudit(audit){
    let show = JSON.parse(audit);
    return show;
  }

  clickLink(link) {
    console.log(link);
  }

  notesIsExists(): boolean {
    return !missingOrEmpty(this.notes);
  }

  processIsExists(): boolean {
    return !missing(this._processInstanceId);
  }


  @Input()
  get processInstanceId(): any {
    return this._processInstanceId;
  }

  set processInstanceId(value: any) {
    if (this._processInstanceId === value) return;
    this._processInstanceId = value;
    this._src = null;
    // if (!this.notesIsExists())
    this.getWorkflowImg();
  }

  onSelect() {
    // if (this.notesIsExists())
      this.getWorkflowImg();
  }

  getWorkflowImg() {
    if (this._src != null) return;
    if (missing(this._processInstanceId)) {
      this._src = null;
      return;
    }
    const data = { processInstanceId: this._processInstanceId, authed: false };
    this.apiService.post('crm.customComplain.getAllProcess', { 'body': JSON.stringify(data) }).subscribe(
      body => {
        // console.log(body);
        if (body) {
          this.candidate = body[0]['candidate'] ? body[0]['candidate'] : '';
          this.curTaskName = body[0]['curTaskName'] ? body[0]['curTaskName'] : '';
          this.nodeDuration = this.toHour(body[0]['nodeDuration']);
          // this.postDate = new Date();
          // this.nodeDuration = body[0]['nodeDuration'];
          // console.log(this.nodeDuration);
        }
      },
    );
    this.apiService.export('wf.getProcessInstancePng', { processInstanceId: this._processInstanceId }).subscribe(
      (body) => {
        if (body.type === 'image/png') {
          let reader = new FileReader();
          let that = this;
          reader.onloadend = function() {
            const data = reader.result;
            that._src = data;
          };
          reader.readAsDataURL(body);
        }
      });
  }

  /** 渲染原数据时间 **/
  getDateTime(datetime) {
    // let date;
    // let days;
    // let nowDate;
    // date = datetime.substring(10);
    // nowDate = distanceInWordsToNow(datetime, {
    //   locale: (window as any).__locale__,
    // });
    // if (isSameDay(new Date(), datetime)) {
    //   days = '今天 ';
    //   return days + nowDate + '前';
    // } else if (isSameDay(datetime, subDays(new Date(), 1))) {
    //   days = '昨天' + date;
    //   return days;
    // } else if (isSameDay(datetime, subDays(new Date(), 2))) {
    //   days = '前天' + date;
    //   return days;
    // } else {
    //   return datetime;
    // }
    return datetime;
  }

  getTime(datetime){
    // let showTime = this.toHour(datetime);
    // console.log(showTime);
    return datetime;
  }

  openCommentLog() {
    this.showCommentLog = !this.showCommentLog;
  }

  /** 评论 **/
  submitCommentLog() {
    if (this.remark !== '') {
      let data = {
        'remark': this.remark, 'businessType': this.note[0].businessType, 'businessKey': this.note[0].businessKey,
        'operator_id': this.userAuthService.getUserInfoObj().userAccount.id, 'operate': '评论', 'oaFlag': false,
      };
      this.apiService.post('ir.logger.add', { 'body': JSON.stringify(data) }).subscribe(body => {
        if (body) {
          this.showCommentLog = false;
          this.notes.unshift(body);
        }
      });
    } else {
      // this.remark = '';
      this.msg.info(`评论不能为空`);
    }
  }

  cancelCommentLog() {
    this.showCommentLog = false;
  }

  // 转换时间
  toHour(value) {
    let time = '';
    if (value) {
      let data = value / 60 / 1000;
      let a = data >= 0 ? '' : '-';
      data = data >= 0 ? data : -data;

      let day = Math.floor(data / 1440);
      let hour = day >= 0
        ? Math.floor((data - (day * 1440)) / 60)
        : Math.floor(data / 60);
      let minute = hour >= 0
        ? Math.floor(data - (day * 1440) - (hour * 60))
        : data < 0
          ? data
          : Math.floor(data / 60 / 24);

      if (day > 0) {
        time = a + day + '天' + hour + '小时' + minute + '分钟';
      } else if (hour) {
        time = a + hour + '小时' + minute + '分钟';
      } else if (minute) {
        time = a + minute + '分钟';
      }
    }
    return time;
  }
}
